from apps.pay.recordIncomes.baseViews import *
from apps.user.dao import UserDao
from django.db.models import Sum
from decimal import Decimal
from apps.pay.recordIncomesLocked.dao import RecordIncomesLockedDao


def getAllRecordIncomes():
    _list = RecordIncomesDao().findAll().select_related('user', 'fromUser')
    return _list

class RecordIncomesForShopOutMoneyViewSet(BaseRecordIncomesViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = getAllRecordIncomes().filter(scene='outMoney')
        if self.request.user.role.key == 'superAdmin' or self.request.user.role.key == 'admin':
            _list = _list
        else:
            _list = _list.filter(shop__lessee=params.get('lessee'))
        return _list

class RecordIncomesForOutMoneyViewSet(BaseRecordIncomesViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = getAllRecordIncomes().filter(scene='outMoney')
        if self.request.user.role.key == 'superAdmin' or self.request.user.role.key == 'admin':
            _list = _list
        else:
            _list = _list.filter(user__lessee=params.get('lessee'))
        return _list

class RecordIncomesViewSet(BaseRecordIncomesViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = getAllRecordIncomes()
        if self.request.user.role.key == 'superAdmin' or self.request.user.role.key == 'admin':
            _list = _list
        elif self.request.user.role.key == 'shop':
            _list = _list.filter(shop__admins__in=[self.request.user.id])
        else:
            _list = _list.filter(user__lessee=params.get('lessee'))
        return _list

    '''我的钱包'''
    @action(methods=['post'], detail=False)
    def myWallet(self, request):
        params = getRequestParams(request)
        # 积分余额
        incomes = request.user.incomes
        #历史累计收益
        historyIncomes = request.user.historyIncomes
        # 提现中
        outMoneying = RecordIncomes.objects.filter(user=request.user, scene='outMoney', orderStatus='WAIT_SEND',is_delete=0).aggregate(sums=Sum('money'))
        # 累计提现
        historyOutMoney = RecordIncomes.objects.filter(user=request.user, scene='outMoney', orderStatus='FINISH',is_delete=0).aggregate(sums=Sum('money'))
        # 锁仓资产
        _recordIncomesLocked = RecordIncomesLockedDao().findAll().filter((Q(orderStatus='LOCKED') | Q(orderStatus='UNLOCKED')), user=request.user, scene='goldCustom')
        # 结余锁仓本金
        balanceLockedCapital = _recordIncomesLocked.aggregate(sums=Sum('money'))['sums']
        # # 结余锁仓补贴
        balanceLockedSupport = _recordIncomesLocked.aggregate(sums=Sum('money2'))['sums']
        moneyForProperaty = Decimal(balanceLockedCapital) + Decimal(balanceLockedSupport)

        return Response(response_success({
            "incomes": float(incomes),
            "historyIncomes": float(historyIncomes),
            "outMoneying": float(outMoneying['sums']) if outMoneying['sums'] else '0',
            "historyOutMoney": float(historyOutMoney['sums']) if historyOutMoney['sums'] else '0',
            "moneyForProperaty": float(moneyForProperaty) if moneyForProperaty else "0"
        }))

    '''用户提现'''
    @action(methods=['post'], detail=False)
    def outMoneyForUser(self, request):
        params = getRequestParams(request)
        if params.get('paywayType') == 'incomes':
            if not params.get('payWayId'):
                return Response(response_message("未设置默认收款账户！"))
            elif Decimal(request.user.incomes) < Decimal(params.get('payMoney')):
                return Response(response_message("提现失败！收益余额不足！"))
            elif Decimal(params.get('payMoney')) < request.user.lessee.serviceCharge_min:
                return Response(response_message("提现失败！最小提现金额"+str(request.user.lessee.serviceCharge_min)+"元！"))
            elif Decimal(params.get('payMoney')) > request.user.lessee.serviceCharge_max:
                return Response(response_message("提现失败！最大提现金额"+str(request.user.lessee.serviceCharge_max)+"元！"))
            elif RecordIncomes.objects.filter(user=request.user, scene='outMoney', createTime__date=datetime.datetime.now(), is_delete=0).count()>=request.user.lessee.serviceChargeNum:
                return Response(response_message("每日最多只能发起"+str(request.user.lessee.serviceChargeNum)+"次提现！"))
            else:
                payMoney = Decimal(params.get('payMoney')).quantize(Decimal('0.00'))
                # 减少用户收益
                UserDao().subWallet('incomes', request.user, payMoney)
                # 计算实际到账
                serviceChargeRate = request.user.lessee.serviceChargeRate
                serviceCharge = 0
                if serviceChargeRate > 0:
                    serviceCharge = (payMoney * serviceChargeRate).quantize(Decimal('0.00'))
                realPay = payMoney - serviceCharge
                
                data = {}
                data['lessee'] = request.user.lessee.id
                data['scene'] = 'outMoney'
                data['payWayAccount'] = params.get('payWayId')
                data['user'] = request.user.id
                data['fromUser'] = request.user.id
                data['orderId'] = ''
                data['money'] = payMoney
                data['serviceCharge'] = serviceCharge
                data['realMoney'] = realPay
                data['payway'] = 'incomes'
                data['changeWay'] = 'sub'
                data['orderStatus'] = 'WAIT_SEND'
                RecordIncomesDao().create(data)

        return Response(response_success("操作成功"))

    '''提现确认'''
    @action(methods=['post'], detail=False)
    def confirmOutMoney(self, request):
        params = getRequestParams(request)
        order = RecordIncomesDao().findOneByObjId(params.get('obj_id'))
        if order.orderStatus == 'REFUSE' or order.orderStatus == 'FINISH':
            return Response(response_message("该记录已处理，不可重复操作！"))
        order.__dict__.update({'orderStatus': 'FINISH', 'remark': params.get('remark'), 'outMoneyTime': datetime.datetime.now()})
        order.save()

        return Response(response_success("操作成功"))

    '''提现拒绝'''
    @action(methods=['post'], detail=False)
    def refuseOutMoney(self, request):
        params = getRequestParams(request)
        order = RecordIncomesDao().findOneByObjId(params.get('obj_id'))
        if order.orderStatus == 'REFUSE' or order.orderStatus == 'FINISH':
            return Response(response_message("该记录已处理，不可重复操作！"))
        order.__dict__.update({'orderStatus':'REFUSE', 'remark': params.get('remark'), 'outMoneyTime': datetime.datetime.now()})
        order.save()
        # 提现拒绝，归还积分
        UserDao().addWallet('incomes', order.user, order.money)
        data = {}
        data['lessee'] = request.user.lessee.id
        data['scene'] = 'outMoneyForRefuse'
        data['user'] = order.user.id
        data['fromUser'] = order.user.id
        data['orderId'] = ''
        data['money'] = order.money
        data['payway'] = 'incomes'
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        RecordIncomesDao().create(data)

        return Response(response_success("操作成功"))